<template>
  <div class="app-container">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="库存变动" name="stock">
        <div class="filter-container">
          <el-input
            v-model="listQuery.keyword"
            placeholder="商品名称/编号"
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="handleFilter"
          />
          <el-select v-model="listQuery.type" placeholder="变动类型" clearable class="filter-item" style="width: 130px">
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
            搜索
          </el-button>
          <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleCreate">
            库存变动
          </el-button>
        </div>

        <el-table
          v-loading="listLoading"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column label="商品编号" prop="productId" align="center" width="100" />
          <el-table-column label="商品名称" prop="productName" min-width="150" />
          <el-table-column label="变动类型" width="100" align="center">
            <template slot-scope="{row}">
              <el-tag :type="row.type | typeFilter">
                {{ row.type === 1 ? '入库' : '出库' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="变动数量" width="100" align="center">
            <template slot-scope="{row}">
              <span>{{ row.type === 1 ? '+' : '-' }}{{ row.quantity }}</span>
            </template>
          </el-table-column>
          <el-table-column label="当前库存" width="100" align="center" prop="currentStock" />
          <el-table-column label="操作人" width="100" align="center" prop="operator" />
          <el-table-column label="操作时间" width="180" align="center">
            <template slot-scope="{row}">
              <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" />
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.limit"
          @pagination="getList"
        />
      </el-tab-pane>

      <el-tab-pane label="库存预警" name="alert">
        <div class="filter-container">
          <el-button class="filter-item" type="warning" @click="handleSetAlert">
            设置预警阈值
          </el-button>
        </div>

        <el-table
          v-loading="alertLoading"
          :data="alertList"
          border
          fit
          highlight-current-row
        >
          <el-table-column label="商品编号" prop="productId" align="center" width="100" />
          <el-table-column label="商品名称" prop="productName" min-width="150" />
          <el-table-column label="当前库存" width="100" align="center" prop="currentStock" />
          <el-table-column label="预警阈值" width="100" align="center" prop="alertThreshold" />
          <el-table-column label="状态" width="100" align="center">
            <template slot-scope="{row}">
              <el-tag :type="row.currentStock < row.alertThreshold ? 'danger' : 'success'">
                {{ row.currentStock < row.alertThreshold ? '库存不足' : '库存正常' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="150">
            <template slot-scope="{row}">
              <el-button type="primary" size="mini" @click="handleViewHistory(row)">
                变动记录
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <el-dialog :visible.sync="dialogFormVisible" :title="dialogType === 'stock' ? '库存变动' : '设置预警阈值'">
      <el-form
        ref="dataForm"
        :rules="dialogType === 'stock' ? rules : alertRules"
        :model="dialogType === 'stock' ? temp : alertTemp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <template v-if="dialogType === 'stock'">
          <el-form-item label="商品" prop="productId">
            <el-select v-model="temp.productId" placeholder="请选择商品" filterable>
              <el-option
                v-for="item in productOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="变动类型" prop="type">
            <el-radio-group v-model="temp.type">
              <el-radio :label="1">入库</el-radio>
              <el-radio :label="2">出库</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="变动数量" prop="quantity">
            <el-input-number v-model="temp.quantity" :min="1" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="temp.remark" type="textarea" :rows="2" />
          </el-form-item>
        </template>

        <template v-else>
          <el-form-item label="商品" prop="productId">
            <el-select v-model="alertTemp.productId" placeholder="请选择商品" filterable>
              <el-option
                v-for="item in productOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="预警阈值" prop="threshold">
            <el-input-number v-model="alertTemp.threshold" :min="0" />
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogType === 'stock' ? createData() : setAlertData()">确认</el-button>
      </div>
    </el-dialog>

    <el-dialog title="库存变动记录" :visible.sync="historyDialogVisible" width="800px">
      <el-timeline>
        <el-timeline-item
          v-for="(item, index) in historyList"
          :key="index"
          :type="item.type === 1 ? 'success' : 'danger'"
          :timestamp="item.createTime"
        >
          <h4>{{ item.type === 1 ? '入库' : '出库' }}</h4>
          <p>变动数量：{{ item.type === 1 ? '+' : '-' }}{{ item.quantity }}</p>
          <p>操作人：{{ item.operator }}</p>
          <p>备注：{{ item.remark }}</p>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script>
import { getStockList, updateStock, getProductList, getStockAlertList, setStockAlert, getStockHistory } from '@/api/product'
import { Pagination } from 'element-ui'

export default {
  name: 'StockList',
  components: { Pagination },
  filters: {
    typeFilter(type) {
      const typeMap = {
        1: 'success',
        2: 'danger'
      }
      return typeMap[type]
    }
  },
  data() {
    return {
      activeTab: 'stock',
      dialogType: 'stock',
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        keyword: undefined,
        type: undefined
      },
      typeOptions: [
        { label: '入库', value: 1 },
        { label: '出库', value: 2 }
      ],
      productOptions: [],
      temp: {
        productId: undefined,
        type: 1,
        quantity: 1,
        remark: ''
      },
      dialogFormVisible: false,
      rules: {
        productId: [{ required: true, message: '请选择商品', trigger: 'change' }],
        type: [{ required: true, message: '请选择变动类型', trigger: 'change' }],
        quantity: [{ required: true, message: '请输入变动数量', trigger: 'blur' }]
      },
      alertList: [],
      alertLoading: false,
      historyList: [],
      historyDialogVisible: false,
      alertTemp: {
        productId: undefined,
        threshold: 0
      },
      alertRules: {
        productId: [{ required: true, message: '请选择商品', trigger: 'change' }],
        threshold: [{ required: true, message: '请输入预警阈值', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
    this.getProducts()
    this.getAlertList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getStockList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    getProducts() {
      getProductList().then(response => {
        this.productOptions = response.data.items
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleCreate() {
      this.resetTemp()
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    resetTemp() {
      this.temp = {
        productId: undefined,
        type: 1,
        quantity: 1,
        remark: ''
      }
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateStock(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    getAlertList() {
      this.alertLoading = true
      getStockAlertList().then(response => {
        this.alertList = response.data
        this.alertLoading = false
      })
    },
    handleSetAlert() {
      this.dialogType = 'alert'
      this.alertTemp = {
        productId: undefined,
        threshold: 0
      }
      this.dialogFormVisible = true
    },
    setAlertData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          setStockAlert(this.alertTemp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '设置成功',
              type: 'success',
              duration: 2000
            })
            this.getAlertList()
          })
        }
      })
    },
    handleViewHistory(row) {
      this.historyDialogVisible = true
      getStockHistory(row.productId).then(response => {
        this.historyList = response.data
      })
    }
  }
}
</script>

<style>
.el-timeline-item__timestamp {
  color: #909399;
  line-height: 1;
  font-size: 13px;
}
</style> 